package com.example.capsule_chat0322.connect;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;

import androidx.core.app.ActivityCompat;

import com.example.capsule_chat0322.bean.PositionBean;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.request.PositionRequest;
import com.example.capsule_chat0322.utils.AlterUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author zhuzhiming
 * @Date 2022/5/18 20:14
 */
public class PositionOperation {


    public static void getLocation(Context context, Handler handler) {

        if (!checkGPSIsOpen(context)) {
            return;
        }

        // 位置
        LocationManager locationManager;
        LocationListener locationListener;
        Location location;
        String contextService = Context.LOCATION_SERVICE;
        String provider;
        final double[] lat = new double[1];
        final double[] lon = new double[1];
        locationManager = (LocationManager) context.getSystemService(contextService);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);// 高精度
        criteria.setAltitudeRequired(false);// 不要求海拔
        criteria.setBearingRequired(false);// 不要求方位
        criteria.setCostAllowed(true);// 允许有花费
        criteria.setPowerRequirement(Criteria.POWER_LOW);// 低功耗
        // 从可用的位置提供器中，匹配以上标准的最佳提供器
        provider = locationManager.getBestProvider(criteria, true);
        // 获得最后一次变化的位置
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        locationListener = new LocationListener() {
            public void onStatusChanged(String provider, int status,
                                        Bundle extras) {
                // TODO Auto-generated method stub
            }

            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub
                AlterUtils.alertByToastInMainThread(context, "你的gps已打开");
            }

            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub
                AlterUtils.alertByToastInMainThread(context, "你的gps已关闭");
            }

            public void onLocationChanged(Location location) {
                lat[0] = location.getLatitude();
                lon[0] = location.getLongitude();

                uploadPosition(lon[0], lat[0], null);
               // AlterUtils.alertByToastInMainThread(context, "你的当前位置:" + lat[0] + "  " + lon[0]);

            }
        };
        // 监听位置变化，2秒一次，距离10米以上
        locationManager.requestLocationUpdates(provider, 1000 * 5, 10,
                locationListener);

        location = locationManager.getLastKnownLocation(provider);
        while (location == null) {
            location = locationManager.getLastKnownLocation(provider);
        }
        uploadPosition(location.getLongitude(), location.getLatitude(), handler);

    }


    private static void uploadPosition(double longitude, double latitude, Handler handler) {
        PositionBean positionBean = new PositionBean();
        positionBean.setLongitude(longitude);
        positionBean.setLatitude(latitude);
        String userId = (String) GlobalAssistMap.getObject("userId");
        String field = (String) GlobalAssistMap.getObject("field");
        if (userId == null || field == null) {
            try {
                Thread.sleep(1000);
                userId = (String) GlobalAssistMap.getObject("userId");
                field = (String) GlobalAssistMap.getObject("field");
                if (userId == null || field == null) {
                    Thread.sleep(1000);
                    userId = (String) GlobalAssistMap.getObject("userId");
                    field = (String) GlobalAssistMap.getObject("field");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (userId != null && field != null) {
            positionBean.setUserId(userId);
            positionBean.setField(field);
            @SuppressLint("SimpleDateFormat") String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            positionBean.setUploadTime(time);
            PositionRequest.uploadPosition(positionBean, handler);
        }
    }

    public static boolean checkGPSIsOpen(Context activity) {
        boolean isOpen;
        LocationManager locationManager = (LocationManager) activity
                .getSystemService(Context.LOCATION_SERVICE);
        //通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        //通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        //部分小米手机顶部通知栏的GPS开关关闭，network仍然是true，设置项里的GPS开关其实是开的
        //只有两个GPS开关和AGPS开关都是关的情况才算是关，有一个开就认为是开的
        boolean agps = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || agps) {
            isOpen = true;
        } else {
            isOpen = false;
        }
        return isOpen;
    }
}
